import { Asset, assetManager } from "cc";
import { ResCache } from "./ResCache";
import ResSetting from "./ResSetting";


export class ResCacheAsset<T extends Asset> extends ResCache {
    protected asset!: T | null;

    protected loadFinish(asset: any) {
        if (asset) {
            this.asset = asset;
            this.asset?.addRef();
            asset[ResSetting.Mark] = this;
        }
        super.loadFinish(asset);
    }

    /**
     * 释放资源
     * @returns 
     */
    public release() {
        if (!this.asset) return;
        this.asset.decRef();
        assetManager.releaseAsset(this.asset);
        this.asset = null;
    }

    /**
     * 资源是否有效
     */
    protected isValid(): boolean {
        if (this.asset) {
            if (this.asset.isValid) {
                return true;
            }
            else {
                console.error(`资源变成无效：path=${this.path}`);
                return false;
            }
        }
        else {
            return false;
        }
    }

    /**
     * 检测资源是否需要销毁
     * @param now 
     * @returns 
     */
    public check(now: number): boolean {
        if (!this.asset) return true;
        return this.autoDestroy && this.refCount <= 0 && this.asset.refCount <= 1 && (now - this.tick > ResSetting.MaxFreeTime);
    }
}